import type { App, Directive, DirectiveBinding } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { usePermissionStoreWithOut } from '@/store/modules/permission'

const { t } = useI18n()

export const hasPermission = (value: string | string[]) => {
  const permissionCodes = (usePermissionStoreWithOut().getPermissionCodes || []) as string[]
  if (Array.isArray(value)) return value.some((item) => permissionCodes.includes(item))
  return permissionCodes.includes(value)
}

/**
 * 权限指令
 * 用法1 <el-button v-prem="'xxx'">按钮</el-button>
 * 用法2 <el-button v-prem="['xxx', 'xxxx']">按钮</el-button>
 * 用法3 <el-button v-prem="{ value: 'xxx' }">按钮</el-button>
 * 用法4 <el-button v-prem="{ value: ['xxx', 'xxxx'] }">按钮</el-button>
 * @param el
 * @param binding
 */
const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  let value = binding.value
  if (!value) throw new Error(t('permission.hasPermission'))

  if (typeof value === 'object' && !Array.isArray(value)) value = value.value
  if (
    (Array.isArray(value) && !hasPermission(value)) ||
    (typeof value === 'string' && !hasPermission(value))
  )
    el.parentNode?.removeChild(el)
}

const permissionDirective: Directive = {
  mounted
}

export const setupPermissionDirective = (app: App<Element>) => {
  app.directive('prem', permissionDirective)
}

export default permissionDirective
